import java.util.ArrayList;
import java.util.List;

/**
 * z转换
 * 比如输入字符串为 "LEETCODEISHIRING" 行数为 3 时，排列如下：
 * L   C   I   R
 * E T O E S I I G
 * E   D   H   N
 * 产生出一个新的字符串，比如："LCIRETOESIIGEDHN"。
 */
class Solution {

    public static void main(String[] args) {
        System.out.println(convert2("LEETCODEISHIRING", 3));
    }

    public static String convert(String s, int numRows) {
        //定义矩阵
        int length = s.length();
        if (s.length() < 2 || numRows < 2) {
            return s;
        }
        int size = 2 * numRows - 2;
        //num为块数
        int num = (length - numRows) / size + 1;
        int m = numRows + ((numRows - 1) * (num - 1));
        char[][] chars = new char[m][numRows];
        for (int i = 0; i < numRows; i++) {
            if (i < length) {
                chars[0][i] = s.charAt(i);
            }
        }
        for (int i = numRows + 1; i < length + 1; i++) {
            //判断在第几块的
            int now = (i - numRows) / (size);
            if ((i - numRows) % (size) != 0) {
                now += 1;
            }
            //求出当前值的x和y
            int x = 1;
            int y = 1;
            int target = now * (size) + 1;
            if (i < target) {
                x = numRows + ((numRows - 1) * (now - 1)) + i - target;
                y = target - i + 1;
            } else {
                x = numRows + ((numRows - 1) * (now - 1));
                y = i - target + 1;
            }
            //逐个赋值到矩阵
            chars[x - 1][y - 1] = s.charAt(i - 1);
        }
        //扫描矩阵成新字符串
        StringBuilder result = new StringBuilder();
        for (int j = 0; j < numRows; j++) {
            for (int i = 0; i < m; i++) {
                if (chars[i][j] != '\u0000') {
                    result.append(chars[i][j]);
                }
            }
        }
        return result.toString();
    }

    public static String convert2(String s, int numRows) {

        if (numRows == 1) return s;

        List<StringBuilder> rows = new ArrayList<>();
        for (int i = 0; i < Math.min(numRows, s.length()); i++)
            rows.add(new StringBuilder());

        int curRow = 0;
        boolean goingDown = false;

        for (char c : s.toCharArray()) {
            rows.get(curRow).append(c);
            if (curRow == 0 || curRow == numRows - 1) goingDown = !goingDown;
            curRow += goingDown ? 1 : -1;
        }

        StringBuilder ret = new StringBuilder();
        for (StringBuilder row : rows) ret.append(row);
        return ret.toString();
    }

}